package com.btl.fragment.shequ;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.btl.bean.ZuiXin;
import com.btl.cygf.R;
import com.btl.cygf.TieZiActivity;
import com.btl.sqlite.DbOpService;
import com.btl.sqlite.History;
import com.btl.utils.DownTuUtils;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;

public class ZuireFragment extends Fragment {
	// 刷新
		private PullToRefreshListView mListView;
		private LinkedList<ZuiXin> listItems = new LinkedList<ZuiXin>(); // 数据源集合
	//	private ArrayAdapter<String> mAdapter;
		private MyListAdapter myListAdapter = new MyListAdapter();       // 实例化适配器
		private AsyncHttpClient client;
		private RequestParams params;
		private int v_id;
		private int lastid;
		ImageLoader imageLoader;

		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View messageLayout = inflater.inflate(R.layout.shequ_zuixin_layout,
					container, false);
			return messageLayout;
		}
		
		@Override
		public void setUserVisibleHint(boolean isVisibleToUser) {
			 if(isVisibleToUser){
	             //加载数据
				 getDataRefresh1();
	         }
			super.setUserVisibleHint(isVisibleToUser);
		}
		
		

		@Override
		public void onActivityCreated(@Nullable Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			
			
			/**
			 * 异步加载网络资源信息
			 */
			client = new AsyncHttpClient();
			// 像网络传输的数据
			params = new RequestParams();
			
			imageLoader = ImageLoader.getInstance();
			imageLoader.init(DownTuUtils.getConfig(getActivity()));

			// 链接到网络，获取数据
			//getDataRefresh1();

			mListView = (PullToRefreshListView) getView().findViewById(R.id.expand_list_zuixin);
			mListView.setOnRefreshListener(new OnRefreshListener<ListView>()
					{
				
				@Override
				public void onRefresh(PullToRefreshBase<ListView> refreshView) {
					String label = DateUtils.formatDateTime(getActivity(),
							System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
									| DateUtils.FORMAT_SHOW_DATE
									| DateUtils.FORMAT_ABBREV_ALL);

					// Update the LastUpdatedLabel
					refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

					// Do work to refresh the list here.
					if (mListView.isHeaderShown()) {
						// 下拉刷新
						getDataRefresh1();
					} else if (mListView.isFooterShown()) {
						// 上拉加载
						getDataMore1(v_id);
					}
				}
			});

			mListView.setMode(Mode.BOTH);
			mListView.getLoadingLayoutProxy(false, true).setPullLabel("加载完成");
			mListView.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载");
			mListView.getLoadingLayoutProxy(false, true).setReleaseLabel("上拉以加载");
			
			mListView.getRefreshableView().setAdapter(myListAdapter);
		}

		/**
		 * 连接到网络 获取数据
		 * 
		 * @param pagenow
		 */
		private void getDataRefresh1() {
			// 实例LinkList数据源
			listItems = new LinkedList<ZuiXin>();
			//ZuiXinRefreshJSON sendZuiReRefreshJason.post
			client.post(getResources().getString(R.string.url) +"/CYGF/sendZuiReRefreshJason.post",new JsonHttpResponseHandler() {
						//链接成功做出的反应
						@Override
						public void onSuccess(int statusCode, Header[] headers,
								JSONArray response) {
							System.out.println("----连接到网络----");
							for (int i = 0; i < response.length(); i++) {
								ZuiXin zuiXin = new ZuiXin();
								JSONObject object = response.optJSONObject(i);
								String s1 = object.optString("v_image");
								System.out.println("最热image:" + s1);
								String s2 = object.optString("v_title");
								String s3 = object.optString("v_intro");
								String s4 = object.optString("p_id");
								int s5 = object.optInt("v_dianzan");
								String s6 = object.optString("p_nickname");
								int s7 = object.optInt("v_id");
								zuiXin.setPicture(s1);
								zuiXin.setTitle(s2);
								zuiXin.setInfo(s3);
								if (s6==null){
									zuiXin.setUsername(s4);
								}else {
									zuiXin.setUsername(s6);
								}
								zuiXin.setDianzan(s5);
								zuiXin.setVid(s7);
								lastid = object.optInt("lastid");
								listItems.add(zuiXin);
								// listItems.addFirst(zuiXin);
								zuiXin = null;
								if (i==(response.length()-1)) {
									v_id = object.optInt("v_id");
								}
							}
							// BaseAdapter数据发生改变
							myListAdapter.notifyDataSetChanged();
							mListView.onRefreshComplete();
							super.onSuccess(statusCode, headers, response);
						}
						
						@Override
						public void onFailure(int statusCode, Header[] headers,
								Throwable throwable, JSONObject errorResponse) {
							// TODO Auto-generated method stub
							super.onFailure(statusCode, headers, throwable, errorResponse);
						}

						// 链接网络失败，做出的反应
						@Override
						public void onFailure(int statusCode, Header[] headers,
								Throwable throwable, JSONArray errorResponse) {
							super.onFailure(statusCode, headers, throwable,
									errorResponse);
						}
					});
		}

		/**
		 * 下拉加载更多
		 */
		private void getDataMore1(final int vid) {
			client.post(getResources().getString(R.string.url) +"/CYGF/ZuiReMoreJSON",
					new JsonHttpResponseHandler() {
						// 链接成功做出的反应
						@Override
						public void onSuccess(int statusCode, Header[] headers,
								JSONArray response) {
							Log.i("vid", vid+"");
							Log.i("vid", lastid+"");
							if (vid == lastid) {
								mListView.getLoadingLayoutProxy(false, true).setRefreshingLabel("没有更多选项");
//								mListView.setMode(Mode.DISABLED);
								new GetDataTask().execute();
							} else {
								for (int i = 0; i < response.length(); i++) {
									ZuiXin zuiXin = new ZuiXin();
									JSONObject object = response.optJSONObject(i);
									String s1 = object.optString("v_image");
									String s2 = object.optString("v_title");
									String s3 = object.optString("v_intro");
									String s4 = object.optString("p_id");
									int s5 = object.optInt("v_dianzan");
									String s6 = object.optString("p_nickname");
									int s7 = object.optInt("v_id");
									zuiXin.setPicture(s1);
									zuiXin.setTitle(s2);
									zuiXin.setInfo(s3);
									if (s6==null) {
										zuiXin.setUsername(s4);
									}else {
										zuiXin.setUsername(s6);
									}
									zuiXin.setDianzan(s5);
									zuiXin.setVid(s7);
									listItems.add(zuiXin);
									// listItems.addFirst(zuiXin);
									zuiXin = null;
									if (i==(response.length()-1)) {
										v_id = object.optInt("v_id");
									}
								}
								// BaseAdapter数据发生改变
								myListAdapter.notifyDataSetChanged();
								mListView.onRefreshComplete();
							}
							super.onSuccess(statusCode, headers, response);
						}

						// 链接网络失败，做出的反应
						@Override
						public void onFailure(int statusCode, Header[] headers,
								Throwable throwable, JSONArray errorResponse) {
							super.onFailure(statusCode, headers, throwable,
									errorResponse);
						}
					});
		}

		/**
		 * listview的适配器MyListAdapter
		 */
		private class MyListAdapter extends BaseAdapter {

			class ListItemView {
				public ImageView image;
				public TextView title;
				public TextView info;
				public TextView zuozhe;
				public TextView dianzanshu;
			}

			@Override
			public int getCount() {
				return listItems.size();
			}

			@Override
			public Object getItem(int position) {
				// TODO Auto-generated method stub
				return listItems.get(position);
			}

			@Override
			public long getItemId(int position) {
				// TODO Auto-generated method stub
				return 0;
			}
			@Override
			public View getView(final int position, View convertView, ViewGroup parent) {
				
				mListView.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						SharedPreferences share= getActivity().getSharedPreferences("login"  , Activity.MODE_WORLD_READABLE);
						String username = share.getString("id", "");
						if(!username.equals("")){
							SimpleDateFormat myFmt=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							Date now = new Date();
							History history = new History();
							history.setUsername(username);
							history.setVid(listItems.get(position-1).getVid()+"");
							history.setTitle(listItems.get(position-1).getTitle());
							history.setIntro(listItems.get(position-1).getInfo());
							history.setVtime(myFmt.format(now));
							DbOpService db= new DbOpService(getActivity());
							db.Insert(history);
						}
						Intent intent = new Intent();
						intent.setClass(getActivity(), TieZiActivity.class);
						intent.putExtra("v_id",listItems.get(position-1).getVid()+"");
						startActivity(intent);
					}
				});
				// final int selectID = position;
				// 自定义视图
				ListItemView listItemView = null;
				if (convertView == null) {
					listItemView = new ListItemView();
					// 获取list_item布局文件的视图
					convertView = LayoutInflater.from(getActivity()).inflate(
							R.layout.zuixin_item, null);
					// 获取控件对象
					listItemView.image = (ImageView) convertView
							.findViewById(R.id.zuixin_view);
					listItemView.title = (TextView) convertView
							.findViewById(R.id.zuixin_name);
					listItemView.info = (TextView) convertView
							.findViewById(R.id.zuixin_info);
					listItemView.zuozhe = (TextView) convertView
							.findViewById(R.id.zuixin_zuozhe);
					listItemView.dianzanshu = (TextView) convertView
							.findViewById(R.id.dianzanshu);
					
					// 设置控件集到convertView
					convertView.setTag(listItemView);
				} else {
					listItemView = (ListItemView) convertView.getTag();
				}

				// 设置文字和图片
				
				//imageLoader.DisplayImage(ZuixinFragment.this.listItems.get(position).getPicture(),listItemView.image);
//				listItemView.image.setImageDrawable(getResources().getDrawable(
//						R.drawable.advertising_default_1));
				// listItemView.image.setImageBitmap(new BitmapFactory().decodeByteArray(data, offset, length))
				
				imageLoader.displayImage(ZuireFragment.this.listItems.get(position).getPicture(), listItemView.image,
						DownTuUtils.getOptions());
				
				listItemView.title.setText(ZuireFragment.this.listItems.get(position).getTitle());
				listItemView.info.setText(ZuireFragment.this.listItems.get(
						position).getInfo());
				listItemView.zuozhe.setText(ZuireFragment.this.listItems.get(
						position).getUsername());
				listItemView.dianzanshu.setText(ZuireFragment.this.listItems.get(
						position).getDianzan()+"");
				return convertView;
			}
			
		}

		private class GetDataTask extends AsyncTask<Void, Void, String> {

			// 后台处理部分
			@Override
			protected String doInBackground(Void... params) {
				// Simulates a background job.
				// mListView.getLoadingLayoutProxy(false,
				// true).setRefreshingLabel("没有更多选项");
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
				}
				String str = "Added after refresh...I add";
				return str;
			}

			// 这里是对刷新的响应，可以利用addFirst（）和addLast()函数将新加的内容加到LISTView中
			// 根据AsyncTask的原理，onPostExecute里的result的值就是doInBackground()的返回值
			@Override
			protected void onPostExecute(String result) {

				// 通知程序数据集已经改变，如果不做通知，那么将不会刷新mListItems的集合
				// myListAdapter.notifyDataSetChanged();
				// 32tCall onRefreshComplete when the list has been refreshed.
				mListView.onRefreshComplete();
				super.onPostExecute(result);
			}
		}

}
